using Godot;
using System;
using System.Collections.Generic;

public partial class Loading : Node2D
{
	#region 子组件
	Timer timer;
	AnimationPlayer animationPlayer;
	CanvasLayer canvasLayer;
	TextureRect textureRect;
	MarginContainer marginContainer;
	ColorRect colorRect;
	ProgressBar progressBar;
	#endregion

	List<Texture2D> LoadingBackgrounds = new List<Texture2D>();
	void CacheLoadingBackground()
	{
		for (int i = 0; i < 7; i++)
		{
			LoadingBackgrounds.Add(ResourceLoader.Load<Texture2D>($"{Path.LOADING_ROOT}/loading-{i + 1}.jpg"));
		}
	}

	void RandomBackground()
	{
		var index = GD.RandRange(0, LoadingBackgrounds.Count - 1);
		textureRect.Texture = LoadingBackgrounds[index];
	}

	public override void _Ready()
	{
		base._Ready();
		GetChildComponents();
		CacheLoadingBackground();
	}

	private void GetChildComponents()
	{
		timer = GetNode<Timer>("Timer");
		animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
		canvasLayer = GetNode<CanvasLayer>("CanvasLayer");
		marginContainer = GetNode<MarginContainer>("CanvasLayer/MarginContainer");
		textureRect = GetNode<TextureRect>("CanvasLayer/TextureRect");
		colorRect = GetNode<ColorRect>("CanvasLayer/ColorRect");
		progressBar = GetNode<ProgressBar>("CanvasLayer/MarginContainer/ProgressBar");

		animationPlayer.AnimationFinished += OnAnimationFinishedHandler;
		timer.Timeout += OnTimeoutHandler;
	}

	private void OnTimeoutHandler()
	{
		animationPlayer.Play("fade_out");
	}

	private void OnAnimationFinishedHandler(StringName animName)
	{
		if (animName.ToString() == "fade_in")
		{
			ResourceLoader.LoadThreadedRequest(currentScenePath);
			isLoading = true;
		}
		else if (animName.ToString() == "fade_out")
		{
			GetTree().ChangeSceneToPacked(ResourceLoader.LoadThreadedGet(currentScenePath) as PackedScene);
			textureRect.Hide();
			marginContainer.Hide();
			animationPlayer.Play("leave_in");
		}
		else if (animName.ToString() == "leave_in")
		{
			canvasLayer.Hide();
			// GameManager.Instance.LevelManager.StartLevel();
		}
	}

	string currentScenePath;
	PackedScene currentScene;

	public void StartLoad(string path)
	{
		RandomBackground();
		currentScenePath = path;
		canvasLayer.Show();
		textureRect.Show();
		marginContainer.Show();
		colorRect.Show();
		animationPlayer.Play("fade_in");
	}

	bool isLoading = false;
	Godot.Collections.Array progress = new Godot.Collections.Array();
	ResourceLoader.ThreadLoadStatus status;

	void WatchLoadProgress()
	{
		if (!isLoading) return;
		status = ResourceLoader.LoadThreadedGetStatus(currentScenePath, progress);
		if (status == ResourceLoader.ThreadLoadStatus.InProgress)
		{
			progressBar.Value = progress[0].As<float>();
		}
		else if (status == ResourceLoader.ThreadLoadStatus.Loaded)
		{
			isLoading = false;
			progressBar.Value = 1f;
			timer.Start();
		}
	}

	public override void _Process(double delta)
	{
		base._Process(delta);
		WatchLoadProgress();
	}

}
